package com.eightbears.beboy.ui.merchant.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.SetMealListAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.base.view.picker.DateTimePicker;
import com.eightbears.beboy.entity.CouponsEntity;
import com.eightbears.beboy.entity.ShopDetailEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.chat.DemoHelper;
import com.eightbears.beboy.ui.user.activity.OrderDetailActivity;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;

import java.util.Calendar;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_PAGE_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_SHOPS_LIST;
import static com.eightbears.beboy.base.util.CommonAPI.URL_SUBMIT_BOOKS;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.base.view.picker.DateTimePicker.HOUR_24;
import static com.eightbears.beboy.ui.user.activity.OrderDetailActivity.PARAMS_ORDER_DETAIL;
import static com.eightbears.beboy.ui.user.activity.ShopDetailActivity.PARAMS_MANAGE_INFO;


/**
 * 预定
 */
public class ReservationShopActivity extends BaseActivity implements
        BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    public static final String EVENT_RESERVATION_SUCCESS = "RESERVATION_SUCCESS";

    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.tv_title)
    TextView tv_title;

    private TextView tv_buy_title;
    private ImageView iv_user_head;
    private TextView tv_nickname;
    private TextView tv_date;
    private TextView tv_call;
    private EditText et_num;
    private EditText et_phone;
    private Button btn_submit;

    private int page = 1;
    private boolean isErr = true;
    private int isEnd = 0;
    private String num, phone, date, timeStamp;

    private DateTimePicker picker;
    private ShopDetailEntity.Managers managers;
    private SetMealListAdapter setMealListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reservation_shop);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);

    }

    @Override
    protected void initData() {
        managers = (ShopDetailEntity.Managers) getExtras().get(PARAMS_MANAGE_INFO);
        tv_title.setText(getString(R.string.text_reservation));
        initAdapter();
        getData();
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    private void initAdapter() {
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        rv_list.setLayoutManager(new MyLinearLayoutManager(this));
        setMealListAdapter = new SetMealListAdapter();
        setMealListAdapter.openLoadAnimation();
        setMealListAdapter.setHeaderView(getHeaderView());
        setMealListAdapter.setOnLoadMoreListener(this);
        rv_list.setAdapter(setMealListAdapter);
        setMealListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                CouponsEntity.Coupons coupons = (CouponsEntity.Coupons) adapter.getData().get(position);
                coupons.setManagers(managers);
                switch (view.getId()) {
                    case R.id.ll_item:
                    case R.id.tv_shopbook_mealbug:
                        startLocalActivity(ReservationShopActivity.this,
                                OrderDetailActivity.class, PARAMS_ORDER_DETAIL, coupons);
                        break;
                }
            }
        });
    }

    private View getHeaderView() {
        View view = getLayoutInflater().inflate(R.layout.view_reservation_head, null);
        tv_buy_title = (TextView) view.findViewById(R.id.tv_buy_title);
        iv_user_head = (ImageView) view.findViewById(R.id.iv_user_head);
        tv_nickname = (TextView) view.findViewById(R.id.tv_nickname);
        tv_call = (TextView) view.findViewById(R.id.tv_call);
        et_num = (EditText) view.findViewById(R.id.et_num);
        et_phone = (EditText) view.findViewById(R.id.et_phone);
        tv_date = (TextView) view.findViewById(R.id.tv_date);
        btn_submit = (Button) view.findViewById(R.id.btn_submit);

        initHeadData();
        initHeadEvent();
        return view;
    }

    private void initHeadData() {
        tv_nickname.setText(managers.getName());
        et_phone.setText(SPUtil.getUser().getData().getMobile());
        CommonUtils.loadImageView(this, managers.getCover(), R.mipmap.icon_default_shop, iv_user_head);
    }

    private void initHeadEvent() {

        initTimePiker();

        tv_call.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtils.call(ReservationShopActivity.this, managers.getMobile());
            }
        });
        tv_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                picker.show();
            }
        });
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkInput()) {
                    sendReservation();
                }
            }
        });
    }

    private void initTimePiker() {
        Calendar selectedDate = Calendar.getInstance();


        picker = new DateTimePicker(ReservationShopActivity.this, HOUR_24);
        picker.setUseWeight(true);
        picker.setDateRangeStart(
                selectedDate.get(Calendar.YEAR),
                selectedDate.get(Calendar.MONTH) + 1,
                selectedDate.get(Calendar.DAY_OF_MONTH));
        picker.setDateRangeEnd(
                selectedDate.get(Calendar.YEAR),
                selectedDate.get(Calendar.MONTH) + 1,
                31
        );
        picker.setSelectedItem(
                selectedDate.get(Calendar.YEAR),
                selectedDate.get(Calendar.MONTH) + 1,
                selectedDate.get(Calendar.DAY_OF_MONTH),
                selectedDate.get(Calendar.HOUR_OF_DAY),
                selectedDate.get(Calendar.MINUTE));
        picker.setCanceledOnTouchOutside(true);
        picker.setOnDateTimePickListener(new DateTimePicker.OnYearMonthDayTimePickListener() {
            @Override
            public void onDateTimePicked(String year, String month, String day, String hour, String minute) {
                date = year + "-" + month + "-" + day + " " + hour + ":" + minute;
                timeStamp = CommonUtils.Date2TimeStamp(date, "yyyy-MM-dd HH:mm");
                tv_date.setText(date);
            }
        });
    }

    private boolean checkInput() {
        num = et_num.getText().toString().trim();
        phone = et_phone.getText().toString().trim();

        if (TextUtils.isEmpty(num)) {
            ShowToast.showShortToast(getString(R.string.alert_reservation_num));
            return false;
        }

        if(Integer.parseInt(num) <= 0) {
            ShowToast.showShortToast("预约人数必须大于0");
            return false;
        }

        if (TextUtils.isEmpty(timeStamp)) {
            ShowToast.showShortToast(getString(R.string.alert_input_reservation_date));
            return false;
        }

        String nowDate = CommonUtils.TimeStamp2Date(String.valueOf(System.currentTimeMillis() / 1000), "yyy-MM-dd HH:mm");
        nowDate = CommonUtils.dateToStamp(nowDate, "yyyy-MM-dd HH:mm");
        if(Integer.parseInt(timeStamp) < Integer.parseInt(nowDate)) {
            ShowToast.showShortToast("预约时间不能小于当前时间");
            return false;
        }

        if (TextUtils.isEmpty(phone)) {
            ShowToast.showShortToast(getString(R.string.alert_please_input_phone_num));
            return false;
        }

        if (!CommonUtils.checkTelephone(phone)) {
            ShowToast.showShortToast(getString(R.string.error_phone_num_input));
            return false;
        }
        return true;
    }

    private void getData() {
        OkHttpUtils.get().url(URL_SHOPS_LIST + managers.getShop_id() + "/coupons")
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("page", String.valueOf(page))
                .addParams("size", PARAMS_PAGE_SIZE)
                .addParams("is_manager", "0").build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                CouponsEntity couponsEntity = GsonUtil.fromJson(response, CouponsEntity.class);
                if (CONNECTION_STATUS_SUCCESS.equals(couponsEntity.getStatus_code())) {
                    isEnd = couponsEntity.getData().getIs_end();
                    if (page == 1) {
                        setMealListAdapter.setNewData(couponsEntity.getData().getList());
                        if (couponsEntity.getData().getList().size() == 0)
                            tv_buy_title.setVisibility(View.GONE);
                        else
                            tv_buy_title.setVisibility(View.VISIBLE);
                    } else {
                        setMealListAdapter.addData(couponsEntity.getData().getList());
                        setMealListAdapter.loadMoreComplete();
                    }
                }

            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ReservationShopActivity.this, status_error);
            }

        });
    }

    private void sendReservation() {
        OkHttpUtils.post().url(URL_SUBMIT_BOOKS)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("shop_id", managers.getShop_id())
                .addParams("manager_user_id", managers.getUser_id())
                .addParams("mobile", phone)
                .addParams("num", num)
                .addParams("time", timeStamp).build()
                .execute(new StringCallback() {

                    @Override
                    public void onResponse(String response) {
                        ShowToast.showShortToast(getString(R.string.alert_reservation_success));
                        EMMessage message = EMMessage.createTxtSendMessage(
                                getString(R.string.text_reservation_submit_success),
                                SPUtil.getUser().getData().getUser_id());
                        message.setFrom("8");
                        DemoHelper.getInstance().getNotifier().onNewMsg(message);
                        EMClient.getInstance().chatManager().sendMessage(message);
                        EventBus.getDefault().post(EVENT_RESERVATION_SUCCESS);
                        finish();
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        KLog.e(e.getMessage());
                        Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                        ErrorUtils.alertError(ReservationShopActivity.this, status_error);
                    }
                });
    }


    @Override
    public void onRefresh() {
        setMealListAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isErr = true;
                page = 1;
                setMealListAdapter.getData().clear();
                getData();
                setMealListAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    setMealListAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        getData();
                    } else {
                        isErr = true;
                        Toast.makeText(getApplication(), R.string.network_anomalies, Toast.LENGTH_LONG).show();
                        setMealListAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }
}
